package com.qidian.by.sso.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
/**
 * Author: 小可怎么都睡不够
 * Date: 2024-04-23 10:25
 * company: 起点编程
 **/
@Component
public class JWTUtil {

    @Value("${secret}")
    private String secret = "system-secret"; // 秘钥

    /**
     * 获取token
     * @param map map中就是有效荷载
     * @return
     */
    public String getToken(Map<String,String> map,int time){
        JWTCreator.Builder builder = JWT.create();
        // 设置客户的payload
        map.forEach((k,v)->{
            builder.withClaim(k, v);
        });
        // 获取过期时间
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND, time);
        // 设置过期时间
        builder.withExpiresAt(instance.getTime());
        // 生成token
        return builder.sign(Algorithm.HMAC256(secret));
    }

    // 验证token的合法性
    // 一旦出现异常就说明验证失败，没有异常就验证成功
    public DecodedJWT checkToken(String token){
        return JWT.require(Algorithm.HMAC256(secret)).build().verify(token);
    }

    /**
     * 获取token中的数据信息
     * @param token
     * @return
     */
    public Map<String, Claim> getTokenInfo(String token){
        return JWT.require(Algorithm.HMAC256(secret)).build().verify(token).getClaims();
    }

    public Map<String, String> getTokenInfoForString(String token){
        Map<String, Claim> tokenInfo = getTokenInfo(token);
        Map<String,String> map = new HashMap<>();
        for (String key : tokenInfo.keySet()){
            map.put(key,tokenInfo.get(key).asString());
        }
        return map;
    }
}
